package cn.weekimwee.firstlineofcodeforkotlin.unit5

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Bundle
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import org.jetbrains.anko.toast

class Demo1Activity : BaseActivity() {
    lateinit var r :NetworkChangeReceiver
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_demo1)
        r = NetworkChangeReceiver()
        registerReceiver(r, IntentFilter().apply {
            addAction("android.net.conn.CONNECTIVITY_CHANGE")
        })

    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(r)
    }

    inner class NetworkChangeReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val networkInfo  = (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
            if(networkInfo!=null && networkInfo.isAvailable){
                toast("network is available")
            }else{
                toast("network is unavailable")
            }
        }
    }
}
